import os,time,sys,json,yaml,shutil

script_run_dir=os.path.dirname(__file__)
# print("cwd:",os.getcwd(),__file__)
app_dir=script_run_dir
os.chdir(app_dir)
app_tmp_dir=app_dir
os.environ['PATH']=";".join([os.path.join(app_dir,"env",'Scripts'),os.path.join(app_dir,"env",'split'),os.path.join(app_dir,"env",'ffmpeg','bin'),os.environ['PATH']])
# print("path:",os.environ['PATH'])
if app_dir not in sys.path:
    sys.path.append(app_dir)
    pass

def rd(file):
    return os.path.join(app_dir,file)
    pass
def file_check_dirs(filename):
    filedir = mkdirs(os.path.dirname(filename))
    return filename
def mkdirs(topath):
    if not os.path.exists(topath):
        os.makedirs(topath)
    return topath
def save_json(jsonfile, jsondata, topath=None):
    if topath is None:
        tofile=jsonfile
    else:
        tofile = file_check_dirs(os.path.join(topath, jsonfile))
    with open(tofile, 'w', encoding='utf-8') as openfile:
        json.dump(jsondata, openfile, ensure_ascii=False)

def get_json(jsonfile, default: dict = None, topath=None):
    if topath is None:
        tofile=jsonfile
    else:
        tofile = file_check_dirs(os.path.join(topath, jsonfile))
    if os.path.exists(tofile):
        with open(tofile, 'r', encoding='utf-8') as openfile:
            return json.load(openfile)
    return default

def save_yaml(yamlfile, data: dict = {}, topath=None):
    if topath is None:
        tofile=yamlfile
    else:
        tofile = file_check_dirs(os.path.join(topath, yamlfile))
    with open(tofile, "w", encoding='utf-8') as openfile:
        yaml.dump(data, openfile, allow_unicode=True)

def get_yaml(yamlfile, default: dict = None, topath=None):
    if topath is None:
        tofile=yamlfile
    else:
        tofile = file_check_dirs(os.path.join(topath, yamlfile))
    if os.path.exists(tofile):
        with open(tofile, 'r', encoding='utf-8') as openfile:
            try:
                res = yaml.load(openfile.read(), Loader=yaml.FullLoader)
            except:
                print("载入yaml异常:", tofile)
                res = None
                pass
            if res is None:
                return default
            return res
    return default
def list_file_path(dir_path, regex="G_*.pth"):
    import glob
    f_list = glob.glob(os.path.realpath( os.path.join(dir_path, regex)))
    f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
    # x = f_list[-1]
    return f_list
app=None
def start_api():
    from fastapi import FastAPI, Body, HTTPException, Request, Response,APIRouter, Depends
    from pydantic import BaseModel, Field
    app = FastAPI()
    @app.get("/")
    def read_root():
        return {"title": "bert vits1 wav fastapi"}
    
    @app.get("/ping")
    def ping():
        return {"ping": time.time()}
    pass
    class SplitStep1Config(BaseModel):
        input_folder:str="input"
        output_folder:str="output"
        sample_rate:int=44100
        mono:bool=True
        use_subtitle_as_name:bool=False
    class SplitStep2Config(BaseModel):
        ban_file:str="ban.txt"
        filter_english: bool=True
    class SplitStep3Config(BaseModel):
        max: int=0
    class SplitConfig(BaseModel):
        srtfile:str="D:/work/ai/Alice_split_toolset/input/tmp.srt"
        wavfile:str="D:/work/ai/Alice_split_toolset/input/tmp.wav"
        step1:SplitStep1Config
        step2:SplitStep2Config
        step3:SplitStep3Config
    @app.post("/split")
    def split(args:SplitConfig):
        try:
            import subprocess
            # set path=./env/Scripts;./env/split;./env/ffmpeg/bin;%path%
            # envs=list()
            
            from split import split_wav_by_srt
            # step1
            print("args:",args)
            srtfile=os.path.realpath(args.srtfile)
            wavfile=os.path.realpath(args.wavfile)
            print(f"split: {wavfile} srt:{srtfile}")
            if not os.path.exists(srtfile) or not os.path.exists(wavfile):
                raise Exception("字幕或者音频文件不存在.")
                pass
            
            wavname= os.path.basename(wavfile)[:-4]
            
            argsstep1=args.step1
            ourfolder=os.path.join(app_dir, argsstep1.output_folder,wavname)
            
            
            print("step1 start.",argsstep1)
            split_wav_by_srt(srtfile, wavfile, argsstep1.output_folder,
                                            argsstep1.sample_rate, argsstep1.mono, argsstep1.use_subtitle_as_name)
            print("step1 ok.")
            
            
            argsstep2=args.step2
            print("step2 start.",argsstep2)
            from clean_list import process_mapping
            process_mapping(os.path.join(ourfolder,"mapping.list"), argsstep2.filter_english, argsstep2.ban_file)
            print("step2 ok.")
            
            
            argsstep3=args.step3
            if argsstep3.max>0:
                print("step3 start.",argsstep3)
                from merge import merge_segments
                merge_segments(os.path.join(ourfolder,"clean_mapping.list"), ourfolder, argsstep3.max)
                print("step3 ok.")
            else:
                print("step3 ignore.",argsstep3.max)
            
            return {"status":"success","message":"视频分割: ok","res":ourfolder}
        except Exception as e:
            return HTTPException(status_code=503,detail="处理异常:"+str(e))
            pass
        pass
    return app
if __name__=="__main__":
    # uvicorn.exe launch:start_api --reload
    import uvicorn,argparse,sys
    parser = argparse.ArgumentParser()
    print("请执行:uvicorn.exe launch:start_api --reload")
    parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0", help="Specify the IP address to listen on (default: 127.0.0.1). If --listen is provided without an argument, it defaults to 0.0.0.0. (listens on all)")
    parser.add_argument("--port", type=int, default=8588, help="Set the listen port.")
    parser.add_argument("--reload",default=False,action="store_true", help="Set reload app.")
    args = parser.parse_args(sys.argv[1:])
    app=start_api()
    # ,reload=True,workers=1
    print("start:",args)
    if args.reload:
        uvicorn.run(app="launch:start_api", host=args.listen, port=args.port, reload=True,factory=True)
    else:
        uvicorn.run(app, host=args.listen, port=args.port)
    
    # uvicorn.run(app="launch:start_api", host=args.listen, port=args.port, reload=True,factory=True)
    